﻿using System.Collections.Generic;
using System.Reflection;
using System.Text;
using smp.QueryDb.Structure;

namespace smp.QueryDb
{
    internal class Group
    {
        private readonly PropertyInfo _property;
        private Column _column;

        internal Group(PropertyInfo property)
        {
            _property = property;
        }

        internal Group(Column column)
        {
            _column = column;
        }

        internal void AppendStatementBuilder(List<Map> maps,  StringBuilder statement, Table table)
        {
            if (_column == null)
            {
                if (_property == null)
                    return;

                var mapColumn = Helper.GetMapColumn(_property, maps);
                if (mapColumn == null)
                {
                    throw Helper.Error("Invalid Group by property : {0}, you must supply a map to the column",
                        _property.Name);
                }
                _column = mapColumn;
            }

            if (!table.IsTableDeclared(_column.TableDeclaration))
            {
                throw Helper.Error("Invalid Group by column : {0}, table declaration {1} is not defined in from call.",
                             _column.Name,
                             _column.TableDeclaration);
            }

            statement.AppendFormat(" {0},", _column.Declaration);
        }
    }
}
